<template>
  <div class="cart">
    <h4>全部商品</h4>
    <div class="cart-main">
      <div class="cart-th">
        <div class="cart-th1">全部</div>
        <div class="cart-th2">商品</div>
        <div class="cart-th3">单价（元）</div>
        <div class="cart-th4">数量</div>
        <div class="cart-th5">小计（元）</div>
        <div class="cart-th6">操作</div>
      </div>
      <div class="cart-body">
        <ul class="cart-list" v-for="cart in cartInfoList" :key="cart.id">
          <!-- 选中 -->
          <li class="cart-list-con1">
            <input type="checkbox" name="chk_list" :checked="cart.isChecked == 1" @change="upDateCheck(cart, $event)" />
          </li>
          <!-- 图片 -->
          <li class="cart-list-con2">
            <router-link :to="`/detail/${cart.skuId}`">
              <img :src="cart.imgUrl" />
              <div class="item-msg">
                {{ cart.skuName }}
              </div>
            </router-link>
          </li>
          <!-- 价格 -->
          <li class="cart-list-con4">
            <span class="price">{{ cart.skuPrice }}.00</span>
          </li>
          <!-- 数量加减 -->
          <li class="cart-list-con5">
            <a href="javascript:void(0)" class="mins" @click="handle('minus', -1, cart)">-</a>


            <input autocomplete="off" type="text" :value="cart.skuNum" minnum="1" class="itxt"
              @change="handle('change', $event.target.value * 1, cart)" />

            <a href="javascript:void(0)" class="plus" @click="handle('add', 1, cart)">+</a>
          </li>
          <!-- 小计 -->
          <li class="cart-list-con6">
            <span class="sum">{{ cart.skuNum * cart.skuPrice }}</span>
          </li>
          <!-- 删除操作 -->
          <li class="cart-list-con7">
            <a class="sindelet" @click="deleteCart(cart)">删除</a>

            <br />
            <a href="#none">移到收藏</a>
          </li>
        </ul>
      </div>
    </div>
    <!-- 下面部分 -->
    <div class="cart-tool">
      <div class="select-all">
        <!-- cartInfoList.length 至少有一个产品时才勾选，这里有问题？？ -->
        <input class="chooseAll" type="checkbox" :checked="isAllChecked && cartInfoList.length > 0"
          @change="isAlllist" />
        <span>全选</span>
      </div>
      <div class="option">
        <a @click="deleteAllChecked">删除选中的商品</a>
        <a href="#none">移到我的关注</a>
        <a href="#none">清除下柜商品</a>
      </div>
      <div class="money-box">
        <div class="chosed">已选择 <span> {{totalNum}} </span>件商品</div>
        <div class="sumprice">
          <em>总价（不含运费） ：</em>
          <i class="summoney">{{ totalPrice }}</i>
        </div>
        <div class="sumbtn">
          <router-link class="sum-btn" to="/trade">结算</router-link>
        </div>
      </div>
    </div>
  </div>
</template>
  
<script>
import { mapGetters } from "vuex";
  // 引入节流函数
import throttle from "lodash/throttle";
export default {
    name: "ShopCart",
    mounted() {
      // 这里通过方法访问仓库，而不是直接访问，目的是防止页面一触发就访问接口
      this.getData();
    },
    computed: {
      ...mapGetters({
        cartList:"shopcart/cartList", //使用了命名空间，需要写位置
      }),
      // 购物车数据
      cartInfoList() {
        return this.cartList.cartInfoList || [];
      },
          // 全选框
      isAllChecked() {
        return this.cartInfoList.every((item) => item.isChecked == 1);
      },
      // 总数
      totalNum(){
        let sum = 0;
        this.cartInfoList.forEach((item) => {
          if (item.isChecked == 1) sum += item.skuNum;
        });
        return sum;
      },
      // 总价
      totalPrice() {
        let sum = 0;
        this.cartInfoList.forEach((item) => {
          if (item.isChecked == 1) sum += item.skuNum * item.skuPrice;
        });
        return sum;
      },
      },

    
methods:{
      getData(){
      this.$store.dispatch('shopcart/getCartList'); //使用了命名空间shopcart/
      },
      // 点击全选框改变小选框
      isAlllist(event) {
        let bossChecked = event.target.checked ? 1 : 0;
        this.cartInfoList.forEach(async (item) => {
          if (item.isChecked != bossChecked) {
            await this.$store.dispatch("shopcart/updataCheckCartById", {
              skuId: item.skuId,
              isChecked: bossChecked,
            });
            this.getData();
          }
        });
      },

        // 修改数量 节流
      handle: throttle(async function (type, disNum, cart) {
        switch (type) {
          case "add":
            disNum = 1;
            break;
          case "minus":
            disNum = cart.skuNum > 1 ? -1 : 0;
            break;
          case "change":
            if (isNaN(disNum) || disNum < 1) {
              disNum = 0;
            } else {
              disNum = parseInt(disNum) - cart.skuNum;
            }
            break;
        }
        try {
          // 向details/下的getAddOrUpdateShopCart接口获取数据，
          await this.$store.dispatch("details/getAddOrUpdateShopCart", {
            skuId: cart.skuId,
            skuNum: disNum,
          });
          // 以此来刷新本页面的数据
          this.getData();

        } catch (error) {
          alert(error.message);
        }
      }, 1000),
  
      // 从购物车里删除对应的单个产品
      async deleteCart(cart) {
        try {
          await this.$store.dispatch("shopcart/deleteCartById", cart.skuId);
          this.getData();
        } catch (error) {
          alert(error.message);
        }
      },
      // 修改小选框状态
      async upDateCheck(cart, event) {
        try {
          let checked = event.target.checked ? "1" : "0";
          await this.$store.dispatch("shopcart/updataCheckCartById", {
            skuId: cart.skuId,
            isChecked: checked,
          });
          this.getData();
        } catch (error) {
          alert(error.message);
        }
      },

      // 删除选中的所有商品
      // 没有删除所有选中商品的接口，可以利用单个删除接口来实现
      async deleteAllChecked() {
        try {
          await this.$store.dispatch("shopcart/deleteAllCartById");
          this.getData();
        } catch (error) {
          alert(error.message);
        }
      },
    },

    }
</script>

  <style lang="css" scoped>
  .cart {
    width: 1200px;
    margin: 0 auto;
  }
  
  .cart h4 {
    margin: 9px 0;
    font-size: 14px;
    line-height: 21px;
  }
  
  .cart .cart-main .cart-th {
    background: #f5f5f5;
    border: 1px solid #ddd;
    padding: 10px;
    overflow: hidden;
  }
  
  .cart .cart-main .cart-th>div {
    float: left;
  }
  
  .cart .cart-main .cart-th .cart-th1 {
    width: 25%;
  }
  
  .cart .cart-main .cart-th .cart-th1 input {
    vertical-align: middle;
  }
  
  .cart .cart-main .cart-th .cart-th1 span {
    vertical-align: middle;
  }
  
  .cart .cart-main .cart-th .cart-th2 {
    width: 25%;
  }
  
  .cart .cart-main .cart-th .cart-th3,
  .cart .cart-main .cart-th .cart-th4,
  .cart .cart-main .cart-th .cart-th5,
  .cart .cart-main .cart-th .cart-th6 {
    width: 12.5%;
  }
  
  .cart .cart-main .cart-body {
    margin: 15px 0;
    border: 1px solid #ddd;
  }
  
  .cart .cart-main .cart-body .cart-list {
    padding: 10px;
    border-bottom: 1px solid #ddd;
    overflow: hidden;
  }
  
  .cart .cart-main .cart-body .cart-list>li {
    float: left;
  }
  
  .cart .cart-main .cart-body .cart-list .cart-list-con1 {
    width: 15%;
  }
  
  .cart .cart-main .cart-body .cart-list .cart-list-con2 {
    width: 35%;
  }
  
  .cart .cart-main .cart-body .cart-list .cart-list-con2 img {
    width: 82px;
    height: 82px;
    float: left;
  }
  
  .cart .cart-main .cart-body .cart-list .cart-list-con2 .item-msg {
    float: left;
    width: 150px;
    margin: 0 10px;
    line-height: 18px;
  }
  
  .cart .cart-main .cart-body .cart-list .cart-list-con4 {
    width: 10%;
  }
  
  .cart .cart-main .cart-body .cart-list .cart-list-con5 {
    width: 17%;
  }
  
  .cart .cart-main .cart-body .cart-list .cart-list-con5 .mins {
    border: 1px solid #ddd;
    border-right: 0;
    float: left;
    color: #666;
    width: 6px;
    text-align: center;
    padding: 8px;
  }
  
  .cart .cart-main .cart-body .cart-list .cart-list-con5 input {
    border: 1px solid #ddd;
    width: 40px;
    height: 33px;
    float: left;
    text-align: center;
    font-size: 14px;
  }
  
  .cart .cart-main .cart-body .cart-list .cart-list-con5 .plus {
    border: 1px solid #ddd;
    border-left: 0;
    float: left;
    color: #666;
    width: 6px;
    text-align: center;
    padding: 8px;
  }
  
  .cart .cart-main .cart-body .cart-list .cart-list-con6 {
    width: 10%;
  }
  
  .cart .cart-main .cart-body .cart-list .cart-list-con6 .sum {
    font-size: 16px;
  }
  
  .cart .cart-main .cart-body .cart-list .cart-list-con7 {
    width: 13%;
  }
  
  .cart .cart-main .cart-body .cart-list .cart-list-con7 a {
    color: #666;
  }
  
  .cart .cart-tool {
    overflow: hidden;
    border: 1px solid #ddd;
  }
  
  .cart .cart-tool .select-all {
    padding: 10px;
    overflow: hidden;
    float: left;
  }
  
  .cart .cart-tool .select-all span {
    vertical-align: middle;
  }
  
  .cart .cart-tool .select-all input {
    vertical-align: middle;
  }
  
  .cart .cart-tool .option {
    padding: 10px;
    overflow: hidden;
    float: left;
  }
  
  .cart .cart-tool .option a {
    float: left;
    padding: 0 10px;
    color: #666;
  }
  
  .cart .cart-tool .money-box {
    float: right;
  }
  
  .cart .cart-tool .money-box .chosed {
    line-height: 26px;
    float: left;
    padding: 0 10px;
  }
  
  .cart .cart-tool .money-box .sumprice {
    width: 200px;
    line-height: 22px;
    float: left;
    padding: 0 10px;
  }
  
  .cart .cart-tool .money-box .sumprice .summoney {
    color: #c81623;
    font-size: 16px;
  }
  
  .cart .cart-tool .money-box .sumbtn {
    float: right;
  }
  
  .cart .cart-tool .money-box .sumbtn a {
    display: block;
    position: relative;
    width: 96px;
    height: 52px;
    line-height: 52px;
    color: #fff;
    text-align: center;
    font-size: 18px;
    font-family: "Microsoft YaHei";
    background: #e1251b;
    overflow: hidden;
  }
  </style>
  